package com.yu.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.util.SystemOutLogger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.yu.model.User;

public class ThreadCraw extends Thread {
	
	private String url;
	
	public ThreadCraw(String url){
		//http://price.pcauto.com.cn/sg1726/baoyang.html
		this.url = url;
	}
	public final static String symbol =",";
	public final static String symbol_space ="\t";
	
	@Override
	public void run() {
		try {
			Document doc = Jsoup.connect(url).userAgent("Chrome").ignoreContentType(true).timeout(60000).get();
			//System.out.println(doc.body().select("iframe").attr("src"));
			Document document = Jsoup.connect(doc.body().select("iframe").attr("src")).userAgent("Chrome").ignoreContentType(true).timeout(60000).get();
			Element body = document.body();
			
			String brand = null;
			String seriers = null;
			
			try {
				Elements title = doc.body().select(".pos-mark a");
				for(int j = title.size() -1 ;j >0;j-- ){
					if (j == title.size() -1){
						seriers = title.get(j).text();
					}
					
					if (j == title.size() -2){
						brand = title.get(j).text();
					}
				}
				/*
				String[] brand_seriers = doc.body().select("h1").text().trim().split("-");
				brand = brand_seriers[0];
				seriers = brand_seriers[1];
				*/
			} catch (Exception e) {
				//e.printStackTrace();
			}
			
			Statement state = DBUtil.getConn().createStatement();
	    	System.out.println("select * from club_handbook where brand ='"+brand+"'"+" and series='"+seriers+"' ");
	    	ResultSet rs = state.executeQuery("select * from club_handbook where brand ='"+brand+"'"+" and series='"+seriers+"' ");
	    	if (rs == null || !rs.next()){
			// 保养项目
			Elements productList = body.select("td.car-td");
			if (productList != null && !StringUtil.isEmpty(productList.text())){
				// 公里数 /月份
				Elements mileageList = body.select("table#scroller th");
				Elements priceList = body.select("table#scroller tr").get(1).select("td");
				StringBuffer content = new StringBuffer("");
				for(int i = 0 ;i < mileageList.size(); i++){
					String mileage_month = mileageList.get(i).text().replaceAll("个", "").trim();
					String mileage = mileage_month.split("KM")[0];
					String month = mileage_month.split("KM")[1].replace("月", "");
					
					String price  = priceList.get(i).text().replaceAll("￥", "").replaceAll("优惠养车","").replaceAll(" ", "") .trim();
					content.append(mileage_month + symbol);
					//System.out.print(mileage_month + symbol_space);
					content.append(price + symbol);
					//System.out.print(price + symbol_space);
					String sump ="";
					for(int j = 2; j < productList.size() ; j++){
						 String productflg =body.select("table#scroller tr").get(j).select("td").get(i).text().replaceAll(" ", "") .trim();
						 if (productflg.trim().length() > 0){
							 DBUtil.addtmp(productList.get(j-1).text().replaceAll(" ", "") .trim());
							 //System.out.println(DBUtil.tmpproduct);
							 sump += productList.get(j-1).text().replaceAll(" ", "") .trim() + symbol;
							 //System.out.println(productList.get(j).text().replaceAll(" ", "") .trim());
							 content.append(productList.get(j-1).text().replaceAll(" ", "") .trim() + symbol);
							 //System.out.print(productList.get(j).text().replaceAll(" ", "") .trim() + symbol_space);
						 }
					}
					if (sump.length() > 0){
						sump = sump.substring(0, sump.length()-1);
					}
					content.append("\n");
					//System.out.println("\n");
					
			    	
		    		double price4s = 0.0;
		    		try{
		    			price4s = Double.valueOf(price);
		    		} catch (Exception e) {
						// TODO: handle exception
					}
		    		state.execute("INSERT INTO `club_handbook` ( `bid`, `brand`, `sid`, `series`, `carid`, `mileage`, `month`, `sumpsubtypes`, `sump`, `price4s`, `createtime`, `valid`) VALUES (0, '"+brand+"', 0, '"+seriers+"', 0, "+mileage+", "+month+", '', '"+sump+"', "+price4s+", "+System.currentTimeMillis()+", 0)");
				}
				
				
				/*
				byte[] buff = new byte[]{};  
	            buff=content.toString().getBytes();  
	            FileOutputStream out=new FileOutputStream("D:///tmp//"+doc.body().select("h1").text().trim()+".csv");  
	            out.write(buff,0,buff.length);*/
			}
	    	}
			//System.out.println(productList.get(2).html());
		} catch (Exception e) {
			System.out.print(url+"");
			e.printStackTrace();
		}
    	
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		new ThreadCraw("http://price.pcauto.com.cn/sg1054/baoyang.html").start();
	
		/*
		Document doc = Jsoup.connect("http://price.pcauto.com.cn/cars/#S").userAgent("Chrome/26.0.1410.64") .timeout(60000).get();
		Element body = doc.body().select("div.iContent").get(0);
 Elements mainDivs = body.select("div.main");
		for(int i = 0 ;i < mainDivs.size() ; i++){

			Elements a = mainDivs.get(i).select("p[class=pTitle]").select("a");
			//System.out.println(a.size());
			for(int j = 0 ;j < a.size() ; j++){
				//System.out.println(a.get(i).attr("href"));
				System.out.println(a.get(j).attr("href"));
				if (a.get(j).attr("href").trim().indexOf("sg21075")>0){
					System.out.println(i);
				}
				////new ThreadCraw("http://price.pcauto.com.cn"+a.get(i).attr("href")+"baoyang.html").start();
				//Thread.sleep(800);
				
			}
		}
		
		//System.out.println(DBUtil.tmpproduct);
	
		DBUtil.closeConn();
		*/
		
	}

}
